<?php

declare(strict_types=1);

namespace Tool\Database;

use Exception as BaseException;
use PDOException;
use Throwable;

/**
 * 数据库异常类.
 */
class Exception extends BaseException
{
    private ?string $sqlState;

    public function __construct(string $message, ?string $sqlState = null, int $code = 0, ?Throwable $previous = null)
    {
        parent::__construct($message, $code, $previous);

        $this->sqlState = $sqlState;
    }

    public function getSQLState()
    {
        return $this->sqlState;
    }

    public static function make(PDOException $exception): self
    {
        if (!is_null($exception->errorInfo)) {
            list($sqlState, $code) = $exception->errorInfo;

            if (is_null($code)) {
                $code = $exception->getCode();
            }
        } else {
            $code = $exception->getCode();
            $sqlState = null;
        }

        return new static($exception->getMessage(), $sqlState, (int) $code, $exception);
    }
}
